1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.collect;
18
19 import com.google.common.annotations.GwtCompatible;
20
21 import java.io.Serializable;
22 import java.util.List;
23
24 import javax.annotation.Nullable;
25
26
27 @GwtCompatible(serializable = true)
28 final class ExplicitOrdering<T> extends Ordering<T> implements Serializable {
29 final ImmutableMap<T, Integer> rankMap;
30
31 ExplicitOrdering(List<T> valuesInOrder) {
32 this(buildRankMap(valuesInOrder));
33 }
34
35 ExplicitOrdering(ImmutableMap<T, Integer> rankMap) {
36 this.rankMap = rankMap;
37 }
38
39 @Override public int compare(T left, T right) {
40 return rank(left) - rank(right);
41 }
42
43 private int rank(T value) {
44 Integer rank = rankMap.get(value);
45 if (rank == null) {
46 throw new IncomparableValueException(value);
47 }
48 return rank;
49 }
50
51 private static <T> ImmutableMap<T, Integer> buildRankMap(
52 List<T> valuesInOrder) {
53 ImmutableMap.Builder<T, Integer> builder = ImmutableMap.builder();
54 int rank = 0;
55 for (T value : valuesInOrder) {
56 builder.put(value, rank++);
57 }
58 return builder.build();
59 }
60
61 @Override public boolean equals(@Nullable Object object) {
62 if (object instanceof ExplicitOrdering) {
63 ExplicitOrdering<?> that = (ExplicitOrdering<?>) object;
64 return this.rankMap.equals(that.rankMap);
65 }
66 return false;
67 }
68
69 @Override public int hashCode() {
70 return rankMap.hashCode();
71 }
72
73 @Override public String toString() {
74 return "Ordering.explicit(" + rankMap.keySet() + ")";
75 }
76
77 private static final long serialVersionUID = 0;
78 }